﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ERPStudio;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Reflection;
using System.Threading;

namespace ESRP
{
    public partial class ArhFormulaContabilaFrm : FrmWorkspace
    {
        private Int16 _genereaza = 0;
        public Int16 GenereazaNC
        {
            get
            {
                return _genereaza;
            }
            set
            {
                _genereaza = value;
            }
        }


        /// <summary>
        /// tipul formulei curente
        /// </summary>
        public int TipFormula = -1;
        ESRPDataSet.BalconSetupRow bsRow = null;
        private ArhNoteContabileRezumatFrm _frmNCR = null;
        private String SerieNumerica = string.Empty;
        /// <summary>
        /// numarul de inregistrari adaugate
        /// </summary>
        private Int32 NoRecAdd = 0;
        /// <summary>
        /// folosit la notele de tip 0 si 1
        /// </summary>
        private String ContComun = String.Empty;

        public ArhFormulaContabilaFrm(ModuleClass mInfo)
            : base(mInfo)
        {
            InitializeComponent();
            workConnString = mInfo.workConnectionString;
            this.HandleBeforeAdd += new EventHandler(RulajeFrm_HandleBeforeAdd);

            #region Handlere functii
            HandleRezumat += new EventHandler(NotaContabilaFrm_HandleRezumat);
            this.HandleAfterAdd += new AfterAddHandler(FormulaContabilaFrm_HandleAfterAdd);
            this.HandleTiparire += Tipareste;
            HandlerValidatingAfterEndEdit += FormulaContabilaFrm_HandlerValidatingAfterEndEdit;

            this.HandleDel += new EventHandler(Sterge);
            arhRulajeDocTableAdapter.Adapter.RowUpdated += new SqlRowUpdatedEventHandler(Adapter_RowUpdated);
            arhRulajeDocTableAdapter.Adapter.RowUpdating += new SqlRowUpdatingEventHandler(Adapter_RowUpdating);
            arhRulajeTableAdapter.Adapter.RowUpdating += new SqlRowUpdatingEventHandler(rulajeAdapter_RowUpdating);
            if (ModuleInfo.AnArhiva != String.Empty)
            {
                if (ModuleInfo.eArhivaEditabila)
                {
                    HandleSalvare += new EventHandler(Salvare);
                }
                else
                    this.ReadOnly = true;
            }
            else
                HandleSalvare += new EventHandler(Salvare);
            #endregion


            #region valori implicite pentru document
            eSRPDataSet.RulajeDoc.CodUnitateColumn.DefaultValue = ModuleInfo.CodUnitate;
            eSRPDataSet.RulajeDoc.TipFormulaColumn.DefaultValue = 2;
            eSRPDataSet.RulajeDoc.ValoareLeiColumn.DefaultValue = 0.0;
            eSRPDataSet.RulajeDoc.ValoareValutaColumn.DefaultValue = 0.0;
            eSRPDataSet.RulajeDoc.DataDocColumn.DefaultValue = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
            eSRPDataSet.RulajeDoc.IDJurnalColumn.DefaultValue = 0;
            #endregion

            #region valori implicite pentru rulaje
            eSRPDataSet.Rulaje.CodValutaColumn.DefaultValue = 0;
            eSRPDataSet.Rulaje.ValoareValutaColumn.DefaultValue = 0;
            eSRPDataSet.Rulaje.CursColumn.DefaultValue = 0;
            eSRPDataSet.Rulaje.CodUnitateColumn.DefaultValue = ModuleInfo.CodUnitate;
            eSRPDataSet.Rulaje.TipDocJustColumn.DefaultValue = String.Empty;
            eSRPDataSet.Rulaje.NumarDocJustColumn.DefaultValue = 0;
            eSRPDataSet.Rulaje.NrCrtColumn.DefaultValue = 0;
            #endregion

            dataDocDTP.Format = DateTimePickerFormat.Custom;
            dataDocDTP.CustomFormat = "dd.MM.yyyy";
            lstPK.Add(numarDocTB);

            #region pentru cand se vor trece conturile pe combo
            /*
            contDebitColumn.DataSource = conturiDebitBindingSource;
            contDebitColumn.DisplayMember = "Cont";
            contDebitColumn.ValueMember = "Cont";

            contCreditColumn.DataSource = conturiCreditBindingSource;
            contCreditColumn.DisplayMember = "Cont";
            contCreditColumn.ValueMember = "Cont";
             * */

            #endregion

            if (ModuleInfo.CurrentTheme == "tribunal")
            {
                ///repozitioneaza controalele
                ///
                numarNotaCB.Location = new Point(numarNotaCB.Location.X + 350, numarNotaCB.Location.Y);
                numarDocTB.Location = new Point(numarDocTB.Location.X + 350, numarDocTB.Location.Y);
                numarDocLabel.Location = new Point(numarDocLabel.Location.X + 350, numarDocLabel.Location.Y);
                numarNotaL.Location = new Point(numarNotaL.Location.X + 350, numarNotaL.Location.Y);
                dataDocLabel.Location = new Point(dataDocLabel.Location.X + 350, dataDocLabel.Location.Y);
                dataDocDTP.Location = new Point(dataDocDTP.Location.X + 350, dataDocDTP.Location.Y);

                jurnalL.Location = new Point(jurnalL.Location.X - 20, 12);
                jurnalL.Text = "Capitolul:";
                jurnalCB1.Location = new Point(jurnalCB1.Location.X, 8);
                jurnalCB2.Location = new Point(80, 32);
                jurnalCB2.Size = new Size(250, jurnalCB2.Size.Height);
                CapitoleB.Visible = true;

                valoareLeiLabel.Location = new Point(valoareLeiLabel.Location.X, 60);
                valoareLeiTextBox.Location = new Point(valoareLeiTextBox.Location.X, 56);
                label1.Location = new Point(label1.Location.X, 60);
                splitContainerPrincipal.SplitterDistance = 80;
                if (!bsRow.DocumentJustifRulaj)
                {
                    ///redimensioneaza coloanele din grid
                    ///
                    valoareLeiColumn.Width = 150;
                    ExplicatiiColumn.Width = 300;
                }
            }
        }

        void Adapter_RowUpdating(object sender, SqlRowUpdatingEventArgs e)
        {
            if (ModuleInfo.AnArhiva != String.Empty && e.StatementType == StatementType.Insert)
            {
                //pentru arhiva trebuie modificata comanda
                e.Command.CommandText = "INSERT INTO [dbo].[RulajeDoc" + ModuleInfo.AnArhiva + "]  ([ValoareLei], [ValoareValuta], [NumarDoc], [DataDoc], [NumarNota], [TipFormula], [IDJurnal], [Observatii], [CodUnitate],[IDDocument]) VALUES (@ValoareLei, @ValoareValuta, @NumarDoc, @DataDoc, @NumarNota, @TipFormula, @IDJurnal, @Observatii, @CodUnitate,(SELECT MAX([IDDocument])+1 FROM [RulajeDoc" + ModuleInfo.AnArhiva + "]));" +
                    "SELECT IDDocument, ValoareLei, ValoareValuta, NumarDoc, DataDoc, NumarNota, TipFormula, IDJurnal, Observatii, CodUnitate FROM RulajeDoc" + ModuleInfo.AnArhiva + " WHERE (IDDocument = (SELECT MAX(IDDocument) FROM [RulajeDoc" + ModuleInfo.AnArhiva + "]))";
            }
        }

        void rulajeAdapter_RowUpdating(object sender, SqlRowUpdatingEventArgs e)
        {
            if (ModuleInfo.AnArhiva != String.Empty && e.StatementType == StatementType.Insert)
            {
                //pentru arhiva trebuie modificata comanda
                e.Command.CommandText = "INSERT INTO [Rulaje" + ModuleInfo.AnArhiva + "] ([ContDebit], [ContCredit], [CodValuta], [IDDocument], [ValoareValuta], [Curs], [ValoareLei], [DataDocJust], [TipDocJust], [NumarDocJust], [ExplicatiiDocJust], [NrCrt], [CodUnitate],[CodFormula]) " +
                    " VALUES (@ContDebit, @ContCredit, @CodValuta, @IDDocument, @ValoareValuta, @Curs, @ValoareLei, @DataDocJust, @TipDocJust, @NumarDocJust, @ExplicatiiDocJust, @NrCrt, @CodUnitate ,(SELECT MAX(CodFormula) + 1 FROM [Rulaje" + ModuleInfo.AnArhiva + "]));";
                //"SELECT CodFormula, ContDebit, ContCredit, CodValuta, IDDocument, ValoareValuta, Curs, ValoareLei, DataDocJust, TipDocJust, NumarDocJust, ExplicatiiDocJust, NrCrt, CodUnitate FROM Rulaje WHERE (CodFormula = (SELECT MAX(CodFormula) FROM [Rulaje" + ModuleInfo.AnArhiva + "]))";
                //daca se lasa si selectul dispar inregistrarile din tabela! si din grid

            }
        }

        private void Adapter_RowUpdated(object sender, SqlRowUpdatedEventArgs args)
        {
            if (args.StatementType == StatementType.Insert)
            {
                if (args.Row.HasVersion(DataRowVersion.Original))
                {
                    /*if (ModuleInfo.AnArhiva != String.Empty)
                        foreach (DataRow row in
                            eSRPDataSet.Rulaje.Select("IDDocument=-1", "IDDocument", DataViewRowState.Added))
                        {
                            row["IDDocument"] = args.Row["IDDocument"];
                        }
                    else*/
                    foreach (DataRow row in
                    eSRPDataSet.Rulaje.Select("IDDocument=" + args.Row["IDDocument", DataRowVersion.Original].ToString(),
                        "IDDocument", DataViewRowState.Added))
                    {
                        row["IDDocument"] = args.Row["IDDocument"];
                    }


                }
                else
                {
                    MessageBox.Show("Nu s-a reusit adaugarea inregistrarii in RulajeDoc!");
                }
            }

        }

        void FormulaContabilaFrm_HandleAfterAdd(object sender, DataGridViewCellEventArgs args)
        {

            SqlCommand cmd = new SqlCommand("", DeschideConexiune(workConnString)); ;
            Object ret = null;
            /*if (ModuleInfo.AnArhiva != String.Empty)
            {
                cmd = new SqlCommand("", DeschideConexiune(workConnString)); 
                cmd.CommandText = "SELECT MAX([IDDocument])+1 FROM [Documente" + ModuleInfo.AnArhiva + "]";
                ret = cmd.ExecuteScalar();
                if (ret != null && ret != DBNull.Value)
                {
                    ESRPDataSet.RulajeDocRow rd = ((DataRowView)rulajeDocBindingSource.Current).Row as ESRPDataSet.RulajeDocRow;
                    if (rd != null)
                    {
                        rd.IDDocument = Convert.ToInt64(ret);
                        newIdArhiva = rd.IDDocument;
                    }
                }
            }*/
            if (SerieNumerica == String.Empty)
            {
                InchideConexiune(cmd.Connection);
                return;
            }
            String valnew = "1";
            if (cmd == null)
                cmd = new SqlCommand("", DeschideConexiune(workConnString));

            cmd.CommandText = "SELECT [UltimulNrFolosit] FROM [SeriiNumerice] WHERE IDSerie='" + SerieNumerica + "' AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            ret = cmd.ExecuteScalar();
            if (ret != null && ret != DBNull.Value)
            {
                valnew = ret.ToString();
            }
            ///incrementarea seriei se face la salvare
            ///
            if (NoRecAdd > 0)
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "ActSeriiNumerice";
                cmd.Parameters.Add(new SqlParameter("IDSerie", SerieNumerica));
                cmd.Parameters.Add(new SqlParameter("CodUnitate", ModuleInfo.CodUnitate));
                cmd.ExecuteNonQuery();
                NoRecAdd--;
            }
            else
                NoRecAdd++;


            InchideConexiune(cmd.Connection);

            this.numarDocTB.Text = valnew;

            ActiveControl = numarDocTB;

        }

        override public void Salvare(object sender, EventArgs args)
        {
            MyTrace("Salvare");
            base.Salvare(this, args);
            if (EroareSalvare)
                return;
            if (SerieNumerica != String.Empty)
                if (NoRecAdd > 0)
                {
                    SqlCommand cmd = new SqlCommand("", DeschideConexiune(workConnString));
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "ActSeriiNumerice";
                    cmd.Parameters.Add(new SqlParameter("IDSerie", SerieNumerica));
                    cmd.Parameters.Add(new SqlParameter("CodUnitate", ModuleInfo.CodUnitate));
                    cmd.ExecuteNonQuery();
                    InchideConexiune(cmd.Connection);
                    NoRecAdd = 0;

                }
            ///calculeaza totalul pentru cazul in care se sterge o linie
            String newVal = GetSum("valoareLeiColumn").ToString("N2");
            if (this.valoareLeiTextBox.Text != newVal)
                this.valoareLeiTextBox.Text = newVal;

            newVal = GetSum("valoareValutaColumn").ToString("N2");
            if (this.valoareValutaTB.Text != newVal)
                this.valoareValutaTB.Text = newVal;

            #region Lansare thread actualizare
            if (NoRecUpdated > 0)
            {
                Thread newThread = new Thread(UpdateSoldCont);
                newThread.Start(workConnString);
            }

            #endregion

        }

        override public void toolStripLabelAnLuna_Click(object sender, EventArgs e)
        {
            ///configurare modul
            #region Configurare Modul BalCon
            FrmMainMdi frm = MdiParent as FrmMainMdi;
            Assembly asm = frm.GetModule("erpforms");
            if (asm == null)
                return;
            String numeClasa = "ERPForms.BalconSetupFrm";
            Type mModule = asm.GetType(numeClasa);

            if (mModule != null)
            {
                FrmCard newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                   new object[] { ModuleInfo }, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmCard;

                newFrm.ShowDialog();
            }
            #endregion
            ///configurare modul-----------------------------------
            this.OnActivated(null);
            ///actualizare unitate la copi
            foreach (Form frmChild in this.MdiParent.MdiChildren)
            {
                //if (frmChild != this)
                ((StudioForm)frmChild).SetCurentMonth(ModuleInfo.CodUnitate);
            }
        }

        override public void SetCurentMonth(short vCodUnitate)
        {
            //Setup();
        }

        private void UpdateSoldCont(object cStr)
        {
            SqlCommand cmd = new SqlCommand("", DeschideConexiune(cStr.ToString()));
            cmd.CommandText = "balcon_UpdateSoldCont";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("codUnitate", ModuleInfo.CodUnitate));
            try
            {
                cmd.ExecuteNonQuery();
            }
            catch
            {

            }
            InchideConexiune(cmd.Connection);
        }

        private void FormulaContabilaFrm_Load(object sender, EventArgs e)
        {
            AddBindingSource(arhRulajeDocBindingSource);
            AddBindingSource(fKarhRulajearhRulajeDocBindingSource); //cheia externa
            AddBindingSource(rulajeSaveBS);

            /// adauga tabelele la lista de adaptoare pentru salvarea in baza de date!
            listTableAdaptor.Add(arhRulajeDocTableAdapter.Adapter);
            listTableAdaptor.Add(arhRulajeTableAdapter.Adapter);

            if (!this.ReadOnly)
            {
                if (ModuleInfo.CurrentTheme == String.Empty)
                {
                    AddButton("Salvare", global::ERPStudio.Properties.Resources.salvare1, Salvare, ToolStripItemAlignment.Right, true);
                    AddButton("Conturi", global::ERPStudio.Properties.Resources._001_07, RezumatConturi, ToolStripItemAlignment.Right, false);
                    AddButton("Copiaza", global::ERPStudio.Properties.Resources.delicious_48, Copiaza, ToolStripItemAlignment.Right, false);
                    List<ToolStripMenuItem> items = new List<ToolStripMenuItem>();
                    AddDropDownItem("Tipareste nota contabila", Tipareste, ref items);
                    AddDropDownItem("Tipareste propunere", TiparestePropunere, ref items);
                    AddDropDownItem("Tipareste angajament bugetar", TiparesteAngajament, ref items);
                    AddDropDownItem("Tipareste angajament legal", TiparesteAngajamentLegal, ref items);
                    AddDropDown("Tipareste[F7]", global::ERPStudio.Properties.Resources.tipareste, (EventHandler)null, items.ToArray(), ToolStripItemAlignment.Right);
                }
                else
                {
                    AddButton("Incarca[F2]", global::ERPStudio.Properties.Resources.note, NotaContabilaFrm_HandleRezumat, ToolStripItemAlignment.Left, true);
                    AddButton("Conturi[F3]", global::ERPStudio.Properties.Resources.prezinta, RezumatConturi, ToolStripItemAlignment.Left, false);
                    AddButton("Sterge[F5]", global::ERPStudio.Properties.Resources.sterge, StergeTribunal, ToolStripItemAlignment.Left, false);

                    List<ToolStripMenuItem> items = new List<ToolStripMenuItem>();
                    AddDropDownItem("Tipareste nota contabila", Tipareste, ref items);
                    AddDropDownItem("Tipareste propunere", TiparestePropunere, ref items);
                    AddDropDownItem("Tipareste angajament bugetar", TiparesteAngajament, ref items);
                    AddDropDownItem("Tipareste angajament legal", TiparesteAngajamentLegal, ref items);
                    AddDropDown("Tipareste[F7]", global::ERPStudio.Properties.Resources.tipareste, (EventHandler)null, items.ToArray(), ToolStripItemAlignment.Left);
                    AddButton("Adauga[F8]", global::ERPStudio.Properties.Resources.adauga, Adauga, ToolStripItemAlignment.Left, false);

                    AddButton("Salvare[F9]", global::ERPStudio.Properties.Resources.salvare, Salvare, ToolStripItemAlignment.Left, true);



                    HandleAdd += RezumatConturi;
                    HandleMoveLast += StergeTribunal;
                    HandleSearch += Tipareste;
                    HandleDel += Adauga;
                    HandleSalvare += Salvare;
                }
            }
            SetCurentUnit(ModuleInfo.CodUnitate);
            if (bsRow.TipUnitate.Trim().ToUpper() == "B")
            {
                List<ToolStripMenuItem> items = new List<ToolStripMenuItem>();
                AddDropDownItem("Tipareste nota contabila", Tipareste, ref items);
                AddDropDownItem("Tipareste propunere", TiparestePropunere, ref items);
                AddDropDownItem("Tipareste angajament bugetar", TiparesteAngajament, ref items);
                AddDropDownItem("Tipareste angajament legal", TiparesteAngajamentLegal, ref items);
                AddDropDown("Tipareste[F7]", global::ERPStudio.Properties.Resources.tipareste, (EventHandler)null, items.ToArray(), ToolStripItemAlignment.Right);
            }

            numarDocTB.Focus();
            ActiveControl = numarDocTB;
            Application.DoEvents();

        }

        private void Setup(SqlConnection wConn)
        {

            SqlCommand com = new SqlCommand("SELECT MIN([IDjurnal]) FROM [Jurnale] WHERE [CodUnitate]=" + ModuleInfo.CodUnitate, wConn);
            Object rId = com.ExecuteScalar();
            if (rId != null && rId != DBNull.Value)
                eSRPDataSet.RulajeDoc.IDJurnalColumn.DefaultValue = Convert.ToInt32(rId);

            while (balconSetupBindingSource.Current == null)
            {
                SqlCommand comcfg = new SqlCommand("INSERT INTO BalconSetup (CodUnitate,AnCurent,LunaCurenta) VALUES (" + ModuleInfo.CodUnitate.ToString() + "," + DateTime.Now.Year.ToString() + "," + DateTime.Now.AddMonths(-1).Month.ToString() + ")",
                    wConn);
                comcfg.ExecuteNonQuery();
                this.OnActivated(null);
                balconSetupTableAdapter.Connection = wConn;
                balconSetupTableAdapter.Fill(eSRPDataSet.BalconSetup, ModuleInfo.CodUnitate);
            }

            bsRow = ((DataRowView)balconSetupBindingSource.Current).Row as ESRPDataSet.BalconSetupRow;
            this.numarNotaCB.Visible = bsRow.FolosesteNota;
            this.numarNotaL.Visible = bsRow.FolosesteNota;
            ///daca nu se foloseste numarul notei v-a avea valoare implicita
            if (!bsRow.FolosesteNota)
                eSRPDataSet.RulajeDoc.Columns["NumarNota"].DefaultValue = String.Empty;


            this.jurnalCB1.Visible = bsRow.FolosesteJurnal;
            this.jurnalCB2.Visible = bsRow.FolosesteJurnal;
            CapitoleB.Visible = (ModuleInfo.CurrentTheme == "tribunal") && bsRow.FolosesteJurnal;
            jurnalL.Visible = bsRow.FolosesteJurnal;

            this.observatiiTB.Visible = bsRow.FolosesteObservatii;
            this.observatiiL.Visible = bsRow.FolosesteObservatii;
            ///activare campuri pentru valute

            valoareValutaTB.Visible = bsRow.FolosesteValute;
            dataDocJustColumn.Visible = bsRow.DocumentJustifRulaj;
            numarDocJustColumn.Visible = bsRow.DocumentJustifRulaj;
            tipDocJustColumn.Visible = bsRow.DocumentJustifRulaj;

            cursColumn.Visible = bsRow.FolosesteValute;
            valoareValutaColumn.Visible = bsRow.FolosesteValute;
            codValutaColumn.Visible = bsRow.FolosesteValute;

            SerieNumerica = bsRow.IsIdSerieNCNull() ? "" : bsRow.IdSerieNC;

            nrCrtColumn.Visible = false;

            this.AddOnlyMaster = bsRow.FaraAdaugareGrid;

            eSRPDataSet.Rulaje.DataDocJustColumn.DefaultValue = new DateTime(bsRow.AnCurent, bsRow.LunaCurenta, 1);

            if (bsRow.TipUnitate == "B")
            {
                jurnalL.Text = "Capitol";
            }

            if (bsRow.LunaCurenta == 0)
            {
                MessageBox.Show("Modulul Balante Contabile nu a fost configurat corect (Luna curenta=0). \nVa rugam sa-l configurati!",
                            "Eroare",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Hand);
                return;
            }

            ///daca este in perioada curenta
            if (ModuleInfo.AnArhiva == String.Empty)
            {
                if (ModuleInfo.CurrentTheme != "tribunal")
                {
                    if (_genereaza == 0)
                    {
                        arhRulajeDocBindingSource.Filter = "[DataDoc] >= '" + bsRow.AnCurent.ToString() + "-" + bsRow.LunaCurenta.ToString() + "-1'";
                        dataDocDTP.MinDate = new DateTime(bsRow.AnCurent, bsRow.LunaCurenta, 1);
                        eSRPDataSet.RulajeDoc.DataDocColumn.DefaultValue = dataDocDTP.MinDate;
                    }
                    SetInfoLunaAnul(bsRow.LunaCurenta.ToString() + "," + bsRow.AnCurent.ToString());
                }
            }


        }

        private void RezumatConturi(object sender, EventArgs e)
        {
            /// rezumatul conturilor nu poate fi afisat decat din capurile 
            /// credit sau debit din formula
            if (this.rulajeDGV.CurrentCell == null ||
                (this.rulajeDGV.CurrentCell.ColumnIndex != this.rulajeDGV.Columns["contCreditColumn"].Index
                    && this.rulajeDGV.CurrentCell.ColumnIndex != this.rulajeDGV.Columns["contDebitColumn"].Index))
            {
                MessageBox.Show("Rezumatul conturilor poate fi afisat doar din campurile credit sau debit", "Eroare",
                 MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }

            ConturiRezumatFrm rez = new ConturiRezumatFrm(ModuleInfo);
            rez.SelectionAddOn = true;
            if (rez.ShowDialog() == DialogResult.OK)
            {
                if (this.rulajeDGV.CurrentCell.ColumnIndex == this.rulajeDGV.Columns["contCreditColumn"].Index
                    || this.rulajeDGV.CurrentCell.ColumnIndex == this.rulajeDGV.Columns["contDebitColumn"].Index)
                {
                    this.rulajeDGV.CurrentCell.Value =
                        rez.selectedRow.Cells["ContColumn"].Value;
                    if (this.rulajeDGV.CurrentCell.IsInEditMode)
                        this.rulajeDGV.EditingControl.Text = rez.selectedRow.Cells["ContColumn"].Value.ToString();
                }
            }
            this.OnActivated(null);

        }

        private void Tipareste(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.AppStarting;
            String numar, data, tip, capitol;

            ESRPDataSet eSRPDS = new ESRPDataSet();
            numar = this.numarDocTB.Text;
            data = this.dataDocDTP.Text;
            tip = this.numarNotaCB.Text;
            capitol = jurnalCB1.Text;
            BindingSource bs = new BindingSource(eSRPDS, "BalconSetup");
            BindingSource bs1 = new BindingSource(eSRPDS, "Rulaje");
            SqlConnection conn = DeschideConexiune(workConnString);
            try
            {
                SqlDataAdapter ta0 = new SqlDataAdapter("SELECT * FROM [arhRulaje] WHERE CodUnitate=" + ModuleInfo.CodUnitate.ToString() + " AND [IDDocument]=" +
                    ((DataRowView)this.arhRulajeDocBindingSource.Current)["IDDocument"].ToString(), conn);
                ta0.Fill(eSRPDS.Rulaje);
                SqlDataAdapter ta = new SqlDataAdapter("SELECT * FROM [BalconSetup] WHERE CodUnitate=" + ModuleInfo.CodUnitate.ToString(), conn);
                ta.SelectCommand.CommandType = CommandType.Text;
                ta.Fill(eSRPDS.BalconSetup);
            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
                Cursor.Current = Cursors.Default;
                return;
            }
            finally
            {
                InchideConexiune(conn);
            }


            PreviewRaportFrm frm = new PreviewRaportFrm("NotaContabilaRep.rdlc", null, ModuleInfo);
            frm.AddDataSource("ESRPDataSet_Rulaje", bs1);
            frm.AddDataSource("ESRPDataSet_BalconSetup", bs);

            frm.AddParameter("Nr", numar, true);
            frm.AddParameter("Data", data, true);
            frm.AddParameter("Capitol", capitol, true);
            frm.AddParameter("Tip", tip, true);

            frm.MdiParent = this.MdiParent;
            frm.Show();
            Cursor.Current = Cursors.Default;
        }

        public void TiparestePropunere(object sender, EventArgs e)
        {
            long IDDoc = 0;
            if (this.arhRulajeDocBindingSource.Current != null)
            {
                ESRPDataSet.RulajeDocRow rdr = ((DataRowView)this.arhRulajeDocBindingSource.Current).Row as ESRPDataSet.RulajeDocRow;
                IDDoc = rdr.IDDocument;
                SqlConnection wConn = DeschideConexiune(workConnString);
                Object ret = GetSetupValue("ExBugSetup", "ContAB", ModuleInfo.CodUnitate, wConn);
                String ContAB = "8066";
                if (ret != null)
                {
                    ContAB = ret.ToString();
                }
                SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM [Rulaje] WHERE IDDocument=" + IDDoc.ToString() +
                    "  AND (ContDebit like '" + ContAB + "%' OR ContCredit like '" + ContAB + "%')", wConn);
                ret = cmd.ExecuteScalar();

                if (ret != null && Convert.ToInt16(ret) == 0)
                {
                    MessageBox.Show("Nota contabile nu poate fi considerata PAC deoarece nu contine contul " + ContAB, "Eroare",
                                     MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
                    InchideConexiune(wConn);
                    return;
                }

                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "exbug_GenereazaPACsiAB";

                cmd.Parameters.Add(new SqlParameter("IDDocument", IDDoc.ToString()));
                cmd.Parameters.Add(new SqlParameter("CodUnitate", ModuleInfo.CodUnitate));
                cmd.Parameters.Add(new SqlParameter("IDPAC", SqlDbType.BigInt, 38, ParameterDirection.Output, false, 38, 0, String.Empty, DataRowVersion.Default, null));
                cmd.Parameters.Add(new SqlParameter("IDAB", SqlDbType.BigInt, 38, ParameterDirection.Output, false, 38, 0, String.Empty, DataRowVersion.Default, null));
                cmd.ExecuteNonQuery();

                Int32 IDPAC = Convert.ToInt32(cmd.Parameters["IDPAC"].Value);
                Int32 IDAB = Convert.ToInt32(cmd.Parameters["IDAB"].Value);

                cmd.Parameters.Clear();
                cmd.CommandText = "CalcDisponibilPAC";
                cmd.Parameters.Add(new SqlParameter("CodUnitate", ModuleInfo.CodUnitate));
                cmd.Parameters.Add(new SqlParameter("IDPAC", IDPAC));
                cmd.Parameters.Add(new SqlParameter("Data", rdr.DataDoc));
                cmd.ExecuteNonQuery();

                ESRPDataSet eSRPDS = new ESRPDataSet();
                Cursor.Current = Cursors.AppStarting;
                String linia1 = String.Empty, linia2 = String.Empty;



                PreviewRaportFrm frm1 = new PreviewRaportFrm("", null, ModuleInfo);
                //eSRPDataSet - este data setul cu care lucram
                List<BindingSource> listBS = new List<BindingSource>();
                List<SqlDataAdapter> listTA = new List<SqlDataAdapter>();

                listBS.Add(new BindingSource(eSRPDS, "BalconSetup"));

                listTA.Clear();
                listTA.Add(new SqlDataAdapter("SELECT * FROM [BalconSetup] WHERE CodUnitate=" + ModuleInfo.CodUnitate.ToString(), cmd.Connection));
                listTA[0].SelectCommand.CommandType = CommandType.Text;
                listTA[0].Fill(eSRPDS.BalconSetup);

                listTA.Add(new SqlDataAdapter("SELECT * FROM [ExBugSetup] WHERE CodUnitate=" + ModuleInfo.CodUnitate.ToString(), cmd.Connection));
                listTA[1].SelectCommand.CommandType = CommandType.Text;
                listTA[1].Fill(eSRPDS.ExBugSetup);
                listBS.Add(new BindingSource(eSRPDS, "ExBugSetup"));

                listTA.Add(new SqlDataAdapter("SELECT * FROM [PropunereAngajareCheltuiala] WHERE IDPAC =" + IDPAC.ToString(), cmd.Connection));
                listTA[2].SelectCommand.CommandType = CommandType.Text;
                listTA[2].Fill(eSRPDS.PropunereAngajareCheltuiala);
                listBS.Add(new BindingSource(eSRPDS, "PropunereAngajareCheltuiala"));

                listTA.Add(new SqlDataAdapter("SELECT * FROM [PropunereAngajareCheltuialaDetaliu] WHERE IDPAC =" + IDPAC.ToString(), cmd.Connection));
                listTA[3].SelectCommand.CommandType = CommandType.Text;
                listTA[3].Fill(eSRPDS.PropunereAngajareCheltuialaDetaliu);
                listBS.Add(new BindingSource(eSRPDS, "PropunereAngajareCheltuialaDetaliu"));



                //String artAl = artAlCB.Text.Substring(0, 2);
                //String diviziune = JurnalCB.Text + "." + GetTitlu(artAl) + "." + artAlCB.Text;


                frm1.NumeRaport = "PropunereAngajare.rdlc";

                frm1.AddDataSource("ESRPDataSet_ExBugSetup", listBS[1]);
                frm1.AddDataSource("ESRPDataSet_BalconSetup", listBS[0]);
                frm1.AddDataSource("ESRPDataSet_PropunereAngajareCheltuiala", listBS[2]);
                frm1.AddDataSource("ESRPDataSet_PropunereAngajareCheltuialaDetaliu", listBS[3]);
                frm1.SetWindowFormat(true);



                foreach (SqlDataAdapter da in listTA)
                    if (da != null) da.Dispose();
                listTA.Clear();
                InchideConexiune(cmd.Connection);
                //frm1.MdiParent = this.MdiParent;
                frm1.ShowDialog();
                //sterge inregistrarile create
                SqlConnection con = DeschideConexiune(workConnString);
                ret = GetSetupValue("ExBugSetup", "StergePACABGenerat", ModuleInfo.CodUnitate, con);
                Boolean sterge = false;
                if (ret != null)
                {
                    sterge = Convert.ToBoolean(ret);
                }
                if (sterge)
                {
                    cmd.Connection = con;
                    cmd.Parameters.Clear();
                    cmd.CommandText = "exbug_StergePACsiAB";
                    cmd.Parameters.Add(new SqlParameter("IDPAC", IDPAC));
                    cmd.Parameters.Add(new SqlParameter("IDAB", IDAB));
                    cmd.ExecuteNonQuery();
                }
                InchideConexiune(cmd.Connection);
                cmd.Dispose();
                Cursor.Current = Cursors.Default;
            }



            /*FrmMainMdi frm = MdiParent as FrmMainMdi;
            Assembly asm = frm.GetModule("exbug");
            if (asm == null)
                return;
            String numeClasa = "ExBug.PACFrm";
            Type mModule = asm.GetType(numeClasa);

            if (mModule != null)
            {

                FrmWorkspace newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                   new object[] { ModuleInfo }, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmWorkspace;

                newFrm.MdiParent = frm;
                newFrm.Show();
                if (newFrm.NoRecAdded != 0 || newFrm.NoRecUpdated != 0)
                {
                    SetCurentUnit(ModuleInfo.CodUnitate);
                }
            }*/
        }

        public void TiparesteAngajament(object sender, EventArgs e)
        {
            List<BindingSource> listBS = new List<BindingSource>();
            List<SqlDataAdapter> listTA = new List<SqlDataAdapter>();
            long IDDoc = 0;
            if (this.arhRulajeDocBindingSource.Current != null)
            {
                ArhESRPDataSet.arhRulajeDocRow rdr = ((DataRowView)this.arhRulajeDocBindingSource.Current).Row as ArhESRPDataSet.arhRulajeDocRow;
                IDDoc = rdr.IDDocument;
                SqlConnection wConn = DeschideConexiune(workConnString);
                Object ret = GetSetupValue("ExBugSetup", "ContAB", ModuleInfo.CodUnitate, wConn);
                String ContAB = "8066";
                if (ret != null)
                {
                    ContAB = ret.ToString();
                }
                SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM [Rulaje] WHERE IDDocument=" + IDDoc.ToString() +
                    "  AND (ContDebit like '" + ContAB + "%' OR ContCredit like '" + ContAB + "%')", wConn);
                ret = cmd.ExecuteScalar();

                if (ret != null && Convert.ToInt16(ret) == 0)
                {
                    MessageBox.Show("Nota contabile nu poate fi considerata PAC deoarece nu contine contul " + ContAB, "Eroare",
                                     MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
                    InchideConexiune(wConn);
                    return;
                }

                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "exbug_GenereazaPACsiAB";

                cmd.Parameters.Add(new SqlParameter("IDDocument", IDDoc.ToString()));
                cmd.Parameters.Add(new SqlParameter("CodUnitate", ModuleInfo.CodUnitate));
                cmd.Parameters.Add(new SqlParameter("IDPAC", SqlDbType.BigInt, 38, ParameterDirection.Output, false, 38, 0, String.Empty, DataRowVersion.Default, null));
                cmd.Parameters.Add(new SqlParameter("IDAB", SqlDbType.BigInt, 38, ParameterDirection.Output, false, 38, 0, String.Empty, DataRowVersion.Default, null));
                cmd.ExecuteNonQuery();

                Int32 IDPAC = Convert.ToInt32(cmd.Parameters["IDPAC"].Value);
                Int32 IDAB = Convert.ToInt32(cmd.Parameters["IDAB"].Value);

                cmd.Parameters.Clear();
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "CalcDisponibilAB";
                cmd.Parameters.Add(new SqlParameter("CodUnitate", ModuleInfo.CodUnitate));
                cmd.Parameters.Add(new SqlParameter("IDAB", IDAB));
                cmd.ExecuteNonQuery();

                ESRPDataSet eSRPDS = new ESRPDataSet();
                Cursor.Current = Cursors.AppStarting;
                String linia1 = String.Empty, linia2 = String.Empty;



                PreviewRaportFrm frm = new PreviewRaportFrm("", null, ModuleInfo);
                //eSRPDataSet - este data setul cu care lucram

                foreach (BindingSource bs in listBS)
                    if (bs != null) bs.Dispose();
                listBS.Clear();
                listBS.Add(new BindingSource(eSRPDS, "BalconSetup"));

                listTA.Clear();
                listTA.Add(new SqlDataAdapter("SELECT * FROM [BalconSetup] WHERE CodUnitate=" + ModuleInfo.CodUnitate.ToString(), cmd.Connection));
                listTA[0].SelectCommand.CommandType = CommandType.Text;
                listTA[0].Fill(eSRPDS.BalconSetup);

                listTA.Add(new SqlDataAdapter("SELECT * FROM [ExBugSetup] WHERE CodUnitate=" + ModuleInfo.CodUnitate.ToString(), cmd.Connection));
                listTA[1].SelectCommand.CommandType = CommandType.Text;
                listTA[1].Fill(eSRPDS.ExBugSetup);
                listBS.Add(new BindingSource(eSRPDS, "ExBugSetup"));

                listTA.Add(new SqlDataAdapter("SELECT * FROM [AngajamentBugetar] WHERE IDAB =" + IDAB.ToString(), cmd.Connection));
                listTA[2].SelectCommand.CommandType = CommandType.Text;
                listTA[2].Fill(eSRPDS.AngajamentBugetar);
                listBS.Add(new BindingSource(eSRPDS, "AngajamentBugetar"));

                listTA.Add(new SqlDataAdapter("SELECT * FROM [AngajamentBugetarDetaliu] WHERE IDAB =" + IDAB.ToString(), cmd.Connection));
                listTA[3].SelectCommand.CommandType = CommandType.Text;
                listTA[3].Fill(eSRPDS.AngajamentBugetarDetaliu);
                listBS.Add(new BindingSource(eSRPDS, "AngajamentBugetarDetaliu"));



                //String artAl = artAlCB.Text.Substring(0, 2);
                //String diviziune = JurnalCB.Text + "." + GetTitlu(artAl) + "." + artAlCB.Text;


                frm.NumeRaport = "AngajamentBugetar.rdlc";

                frm.AddDataSource("ESRPDataSet_ExBugSetup", listBS[1]);
                frm.AddDataSource("ESRPDataSet_BalconSetup", listBS[0]);
                frm.AddDataSource("ESRPDataSet_AngajamentBugetar", listBS[2]);
                frm.AddDataSource("ESRPDataSet_AngajamentBugetarDetaliu", listBS[3]);
                frm.SetWindowFormat(true);



                foreach (SqlDataAdapter da in listTA)
                    if (da != null) da.Dispose();
                listTA.Clear();
                InchideConexiune(cmd.Connection);
                //frm.MdiParent = this.MdiParent;
                frm.ShowDialog();

                //sterge inregistrarile create
                cmd.Connection = DeschideConexiune(workConnString);
                cmd.Parameters.Clear();
                cmd.CommandText = "exbug_StergePACsiAB";
                cmd.Parameters.Add(new SqlParameter("IDPAC", IDPAC));
                cmd.Parameters.Add(new SqlParameter("IDAB", IDAB));
                cmd.ExecuteNonQuery();
                InchideConexiune(cmd.Connection);
                cmd.Dispose();
                Cursor.Current = Cursors.Default;
            }

            /*FrmMainMdi frm = MdiParent as FrmMainMdi;
            Assembly asm = frm.GetModule("exbug");
            if (asm == null)
                return;
            String numeClasa = "ExBug.ABFrm";
            Type mModule = asm.GetType(numeClasa);

            if (mModule != null)
            {

                FrmWorkspace newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                   new object[] { ModuleInfo }, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmWorkspace;

                newFrm.MdiParent = frm;
                newFrm.Show();
                if (newFrm.NoRecAdded != 0 || newFrm.NoRecUpdated != 0)
                {
                    SetCurentUnit(ModuleInfo.CodUnitate);
                }
            }*/
        }

        public void TiparesteAngajamentLegal(object sender, EventArgs e)
        {
            FrmMainMdi frm = MdiParent as FrmMainMdi;
            Assembly asm = frm.GetModule("exbug");
            if (asm == null)
                return;
            String numeClasa = "ExBug.ALFrm";
            Type mModule = asm.GetType(numeClasa);

            if (mModule != null)
            {

                FrmWorkspace newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                   new object[] { ModuleInfo }, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmWorkspace;

                //newFrm.MdiParent = frm;
                newFrm.ShowDialog();
                if (newFrm.NoRecAdded != 0 || newFrm.NoRecUpdated != 0)
                {
                    SetCurentUnit(ModuleInfo.CodUnitate);
                }

            }
        }

        private Int16 GetDisplayTip()
        {
            Int16 ret = 0;
            if (tSB1.Checked)
                ret = 1;
            if (tSB2.Checked)
                ret = 2;
            if (tSB3.Checked)
                ret = 3;
            return ret;
        }

        private void rulajeDGV_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (!rulajeDGV.ContainsFocus)
                return;
            MyTrace(" rulajeDGV_CellValidating rd=" + e.RowIndex.ToString() + ",col=" + e.ColumnIndex.ToString());
            ///Validari
            DataRowView dr = ((DataRowView)arhRulajeDocBindingSource.Current);
            Int16 vTipFormula = GetDisplayTip();
            if (rulajeDGV[e.ColumnIndex, e.RowIndex].ErrorText != String.Empty)
                rulajeDGV[e.ColumnIndex, e.RowIndex].ErrorText = String.Empty;

            ////validare cont introdus in formula contabila
            if (e.ColumnIndex == tipDocJustColumn.Index)
            {
                if (rulajeDGV.EditingControl != null)
                    rulajeDGV.EditingControl.Text = e.FormattedValue.ToString().ToUpper();
                //rulajeDGV[e.ColumnIndex,e.RowIndex].Value = rulajeDGV.CurrentCell.Value.ToString().ToUpper();
            }
            if (contDebitColumn.Index == e.ColumnIndex || e.ColumnIndex == contCreditColumn.Index)
            {
                String cont = string.Empty;
                MyTrace("Cont:" + cont);
                Boolean nuExista = true;

                while (nuExista)
                {
                    cont = rulajeDGV[e.ColumnIndex, e.RowIndex].EditedFormattedValue.ToString();
                    ///DACA nu e nimic in el nu-l validam
                    if (cont.Trim() == String.Empty)
                        return;

                    switch (ExistaContTerminal(cont))
                    {
                        case 1:
                            nuExista = false;
                            break;
                        case 0:
                            if (ExistaContNeTerminal(cont))
                            {
                                if (MessageBox.Show("Contul " + cont + " are analitice. Doriti selectarea unui analitic?", "Selectie", MessageBoxButtons.YesNo, MessageBoxIcon.Hand) == DialogResult.Yes)
                                {
                                    ConturiRezumatFrm rez = new ConturiRezumatFrm(ModuleInfo, GetCategorieCont(cont));
                                    rez.SelectionAddOn = true;
                                    rez.ContParinteSelectat = cont;
                                    if (rez.ShowDialog() == DialogResult.OK)
                                    {
                                        if (this.rulajeDGV.CurrentCell.ColumnIndex == this.rulajeDGV.Columns["contCreditColumn"].Index
                                            || this.rulajeDGV.CurrentCell.ColumnIndex == this.rulajeDGV.Columns["contDebitColumn"].Index)
                                        {
                                            this.rulajeDGV.CurrentCell.Value =
                                                rez.selectedRow.Cells["ContColumn"].Value;
                                            if (this.rulajeDGV.CurrentCell.IsInEditMode)
                                                this.rulajeDGV.EditingControl.Text = rez.selectedRow.Cells["ContColumn"].Value.ToString();
                                        }
                                    }
                                    this.OnActivated(null);
                                }
                                else
                                {
                                    e.Cancel = true;
                                    return;
                                }
                            }
                            else
                            {
                                ///daca exista sintetic sigur vrea sa selecteze un analitic
                                if (ExistaSinteticCont(cont))
                                {
                                    ConturiRezumatFrm rez = new ConturiRezumatFrm(ModuleInfo, GetCategorieCont(cont));
                                    rez.SelectionAddOn = true;
                                    int pozPct = cont.IndexOf('.');
                                    String ContParinte = "N/A";
                                    if (cont.Length > 3 && pozPct == -1)
                                        pozPct = 3;

                                    if (pozPct != -1)
                                    {
                                        ContParinte = cont.Substring(0, pozPct);
                                    }
                                    ///daca contine semnul de intrebare
                                    ///
                                    if (cont.Contains("?") || cont.Contains("+"))
                                    {
                                        int pozIntreb = cont.IndexOf('?');
                                        if (pozIntreb == -1)
                                            pozIntreb = cont.IndexOf('+');
                                        rez.FiltruDenumire = cont.Substring(pozIntreb + 1); ;

                                    }
                                    rez.ContParinteSelectat = ContParinte;
                                    //if (!cont.Contains("?") && !cont.Contains("+"))
                                    //    rez.AdaugaCont = cont;
                                    if (rez.ShowDialog() == DialogResult.OK)
                                    {
                                        if (this.rulajeDGV.CurrentCell.ColumnIndex == this.rulajeDGV.Columns["contCreditColumn"].Index
                                            || this.rulajeDGV.CurrentCell.ColumnIndex == this.rulajeDGV.Columns["contDebitColumn"].Index)
                                        {
                                            this.rulajeDGV.CurrentCell.Value =
                                                rez.selectedRow.Cells["ContColumn"].Value;
                                            if (this.rulajeDGV.CurrentCell.IsInEditMode)
                                                this.rulajeDGV.EditingControl.Text = rez.selectedRow.Cells["ContColumn"].Value.ToString();
                                        }
                                        this.OnActivated(null);

                                    }
                                    else
                                    {
                                        this.OnActivated(null);
                                        e.Cancel = true;
                                        return;
                                    }
                                }
                                else
                                {
                                    MessageBoxFrm mbt = new MessageBoxFrm("Selectie", "Contul " + cont + " inexistent. Doriti selectarea unui alt cont sau adaugarea lui?", "", MessageBoxFrm.ImaginiMB.IntrebareIcon, null);
                                    mbt.AddButton("Adaugare", 70, mbt.MessageBoxFrm_Click_Yes);
                                    mbt.AddButton("Selectie", 70, mbt.MessageBoxFrm_Click_No);
                                    mbt.AddButton("Renuntare", 70, mbt.MessageBoxFrm_Click_Cancel);
                                    DialogResult retD = mbt.ShowDialog();
                                    this.OnActivated(null);
                                    if (retD == DialogResult.Yes)
                                    {
                                        ConturiRezumatFrm rez = new ConturiRezumatFrm(ModuleInfo, GetCategorieCont(cont));
                                        rez.SelectionAddOn = true;
                                        rez.AdaugaCont = cont;
                                        if (rez.ShowDialog() == DialogResult.OK)
                                        {
                                            if (this.rulajeDGV.CurrentCell.ColumnIndex == this.rulajeDGV.Columns["contCreditColumn"].Index
                                                || this.rulajeDGV.CurrentCell.ColumnIndex == this.rulajeDGV.Columns["contDebitColumn"].Index)
                                            {
                                                this.rulajeDGV.CurrentCell.Value =
                                                    rez.selectedRow.Cells["ContColumn"].Value;
                                                if (this.rulajeDGV.CurrentCell.IsInEditMode)
                                                    this.rulajeDGV.EditingControl.Text = rez.selectedRow.Cells["ContColumn"].Value.ToString();
                                            }
                                        }
                                        this.OnActivated(null);
                                    }
                                    else if (retD == DialogResult.No)
                                    {
                                        ConturiRezumatFrm rez = new ConturiRezumatFrm(ModuleInfo, GetCategorieCont(cont));
                                        rez.SelectionAddOn = true;
                                        int pozPct = cont.IndexOf('.');
                                        String ContParinte = "N/A";
                                        if (pozPct != -1)
                                            ContParinte = cont.Substring(0, pozPct);
                                        rez.ContParinteSelectat = ContParinte;
                                        ///daca contine semnul de intrebare
                                        ///
                                        if (cont.Contains("?") || cont.Contains("+"))
                                        {
                                            int pozIntreb = cont.IndexOf('?');
                                            if (pozIntreb == -1)
                                                pozIntreb = cont.IndexOf('+');
                                            rez.FiltruDenumire = cont.Substring(pozIntreb + 1); ;

                                        }
                                        if (rez.ShowDialog() == DialogResult.OK)
                                        {
                                            if (this.rulajeDGV.CurrentCell.ColumnIndex == this.rulajeDGV.Columns["contCreditColumn"].Index
                                                || this.rulajeDGV.CurrentCell.ColumnIndex == this.rulajeDGV.Columns["contDebitColumn"].Index)
                                            {
                                                this.rulajeDGV.CurrentCell.Value =
                                                    rez.selectedRow.Cells["ContColumn"].Value;
                                                if (this.rulajeDGV.CurrentCell.IsInEditMode)
                                                    this.rulajeDGV.EditingControl.Text = rez.selectedRow.Cells["ContColumn"].Value.ToString();
                                            }
                                        }
                                        this.OnActivated(null);
                                    }
                                    else
                                    {
                                        e.Cancel = true;
                                        return;
                                    }

                                }
                            }
                            break;
                        case 2:
                            ///exista parintele lui ca si terminal dar el nu exista...
                            ///
                            if (MessageBox.Show("Contul " + cont + " inexistent. Doriti adaugarea lui?", "Selectie", MessageBoxButtons.YesNo, MessageBoxIcon.Hand) == DialogResult.Yes)
                            {
                                ConturiRezumatFrm rez = new ConturiRezumatFrm(ModuleInfo, GetCategorieCont(cont));
                                rez.SelectionAddOn = true;
                                int pozPct = cont.IndexOf('.');
                                String ContParinte = "N/A";
                                if (pozPct != -1)
                                    ContParinte = cont.Substring(0, pozPct);
                                rez.ContParinteSelectat = ContParinte;
                                rez.AdaugaCont = cont;

                                if (rez.ShowDialog() == DialogResult.OK)
                                {
                                    if (this.rulajeDGV.CurrentCell.ColumnIndex == contCreditColumn.Index
                                        || this.rulajeDGV.CurrentCell.ColumnIndex == contDebitColumn.Index)
                                    {
                                        this.rulajeDGV.CurrentCell.Value =
                                            rez.selectedRow.Cells["ContColumn"].Value;
                                        if (this.rulajeDGV.CurrentCell.IsInEditMode)
                                            this.rulajeDGV.EditingControl.Text = rez.selectedRow.Cells["ContColumn"].Value.ToString();
                                    }
                                }
                                this.OnActivated(null);
                            }
                            else
                            {
                                e.Cancel = true;
                                return;
                            }
                            break;
                    }
                }
            }

            if (e.ColumnIndex == contDebitColumn.Index)
            {
                //pentru prima linie
                if ((e.RowIndex == 0 && vTipFormula < 3) ||
                    ((e.RowIndex > 0) && (vTipFormula == 1 || vTipFormula == 2)))
                {
                    if (rulajeDGV[e.ColumnIndex, e.RowIndex].EditedFormattedValue.ToString().Trim() == String.Empty)
                        rulajeDGV[e.ColumnIndex, e.RowIndex].ErrorText = "Este obligatorie completarea contului debit";
                }
                ///schimba valorile in randurile needitabile
                if ((e.RowIndex == 0 && vTipFormula == 0))
                {
                    for (int ind = 1; ind < rulajeDGV.Rows.Count; ind++)
                    {
                        if ((rulajeDGV[contDebitColumn.Index, ind].Value == null) ||
                            (rulajeDGV[contDebitColumn.Index, ind].Value.ToString() != rulajeDGV[contDebitColumn.Index, 0].EditedFormattedValue.ToString()))
                            rulajeDGV[contDebitColumn.Index, ind].Value = rulajeDGV[contDebitColumn.Index, 0].EditedFormattedValue;
                    }
                    eSRPDataSet.Rulaje.ContDebitColumn.DefaultValue = rulajeDGV.Rows[0].Cells["contDebitColumn"].EditedFormattedValue;
                    eSRPDataSet.Rulaje.ContCreditColumn.DefaultValue = String.Empty;
                }
                if (e.RowIndex > 0 && vTipFormula == 1)
                {
                    //copiaza valoarea fixa
                    if (rulajeDGV[contCreditColumn.Index, e.RowIndex].Value.ToString() != rulajeDGV[contCreditColumn.Index, 0].Value.ToString())
                        rulajeDGV[contCreditColumn.Index, e.RowIndex].Value = rulajeDGV[contCreditColumn.Index, 0].Value;
                }
            }
            if (e.ColumnIndex == contCreditColumn.Index)
            {
                //pentru prima linie
                if ((e.RowIndex == 0 && vTipFormula < 3) ||
                    ((e.RowIndex > 0) && (vTipFormula == 0 || vTipFormula == 2)))
                {
                    if (rulajeDGV[e.ColumnIndex, e.RowIndex].EditedFormattedValue.ToString().Trim() == String.Empty)
                        rulajeDGV[e.ColumnIndex, e.RowIndex].ErrorText = "Este obligatorie completarea contului credit";
                }
                ///schimba valorile in randurile needitabile
                if ((e.RowIndex == 0 && vTipFormula == 1))
                {
                    for (int ind = 1; ind < rulajeDGV.Rows.Count; ind++)
                    {
                        if ((rulajeDGV[contCreditColumn.Index, ind].Value == null) ||
                            (rulajeDGV[contCreditColumn.Index, ind].Value.ToString() != rulajeDGV[contCreditColumn.Index, 0].EditedFormattedValue.ToString()))
                            rulajeDGV[contCreditColumn.Index, ind].Value = rulajeDGV[contCreditColumn.Index, 0].EditedFormattedValue;
                    }
                    eSRPDataSet.Rulaje.ContCreditColumn.DefaultValue = rulajeDGV.Rows[0].Cells["contCreditColumn"].EditedFormattedValue;
                    eSRPDataSet.Rulaje.ContDebitColumn.DefaultValue = String.Empty;
                }
                if (e.RowIndex > 0 && vTipFormula == 0)
                {
                    //copiaza valoarea fixa
                    if (rulajeDGV[contDebitColumn.Index, e.RowIndex].Value.ToString() != rulajeDGV[contDebitColumn.Index, 0].Value.ToString())
                        rulajeDGV[contDebitColumn.Index, e.RowIndex].Value = rulajeDGV[contDebitColumn.Index, 0].Value;
                }
            }


            if (e.ColumnIndex == valoareLeiColumn.Index)
            {
                String valStr = rulajeDGV[e.ColumnIndex, e.RowIndex].EditedFormattedValue.ToString();
                decimal valDec = Decimal.Zero;
                try
                {
                    if (valStr != String.Empty)
                        valDec = Convert.ToDecimal(valStr);
                    if (valDec == Decimal.Zero)
                        rulajeDGV[e.ColumnIndex, e.RowIndex].ErrorText = "Valoare in lei nu poate sa fie 0!";
                }
                catch
                {
                    rulajeDGV[e.ColumnIndex, e.RowIndex].ErrorText = "Va rugam sa introduceti o valoare numerica!";
                }

                //return;
            }
            if (e.ColumnIndex == ExplicatiiColumn.Index)
            {
                if (this.rulajeDGV.EditingControl != null)
                {
                    if (this.rulajeDGV.EditingControl.Text.Trim() == String.Empty)
                        rulajeDGV[e.ColumnIndex, e.RowIndex].ErrorText = "Explicatiile sunt obligatorii!";
                }
                else
                    if (rulajeDGV[e.ColumnIndex, e.RowIndex].Value.ToString().Trim() == String.Empty)
                        rulajeDGV[e.ColumnIndex, e.RowIndex].ErrorText = "Explicatiile sunt obligatorii!";

                //return;
            }
            if (e.ColumnIndex != contDebitColumn.Index && e.ColumnIndex != contCreditColumn.Index)
            {

                // daca se decide formatul notei contabile
                if (fKarhRulajearhRulajeDocBindingSource.Count <= 1)
                {
                    // o nota contabila noua
                    if (e.RowIndex == 0)
                    {
                        ///daca e primul rand
                        ///
                        Int16 tipForm = GetDisplayTip();
                        if (dr["TipFormula"] != DBNull.Value)
                            tipForm = Convert.ToInt16(dr["TipFormula"].ToString());
                        this.FormatFirstRow(tipForm, e.RowIndex, e.ColumnIndex);
                    }

                }
                else
                {
                    // o nota contabila veche cu format cunoscut     
                    //e.Cancel = true;
                    this.FormatNextRows(Convert.ToInt16(dr["TipFormula"].ToString()), e.RowIndex, e.ColumnIndex);
                }
            }
        }

        private Int16 ExistaContTerminal(String cont)
        {
            Int16 ret = 0;
            SqlCommand cmd = new SqlCommand("", FrmRezumat.DeschideConexiune(workConnString));
            cmd.CommandText = "SELECT [Cont] FROM [Conturi] WHERE [Terminal]=1 AND [Cont]='" + cont + "' AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            Object retObj = cmd.ExecuteScalar();
            if (retObj != null && retObj != DBNull.Value)
                ret = 1;
            else
            {
                //daca nu exista cautam sinteticul
                if (cont.Contains("."))
                {
                    String sintetic = cont.Substring(0, cont.IndexOf("."));
                    cmd.CommandText = "SELECT [Cont] FROM [Conturi] WHERE [Terminal]=1 AND [Cont]='" + sintetic + "' AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
                    retObj = cmd.ExecuteScalar();
                    if (retObj != null && retObj != DBNull.Value)
                        ret = 2;
                }
            }
            InchideConexiune(cmd.Connection);
            cmd.Dispose();
            return ret;
        }

        private Boolean ExistaContNeTerminal(String cont)
        {
            Boolean ret = false;
            SqlCommand cmd = new SqlCommand("", FrmRezumat.DeschideConexiune(workConnString));
            cmd.CommandText = "SELECT [Cont] FROM [Conturi] WHERE [Categorie]<>3 AND [Cont]='" + cont + "' AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            Object retObj = cmd.ExecuteScalar();
            if (retObj != null && retObj != DBNull.Value)
                ret = true;
            InchideConexiune(cmd.Connection);
            cmd.Dispose();

            return ret;
        }

        private Boolean ExistaSinteticCont(String cont)
        {
            Boolean ret = false;
            SqlCommand cmd = new SqlCommand("", FrmRezumat.DeschideConexiune(workConnString));
            int pozPct = cont.IndexOf('.');
            if (pozPct == -1)
            {
                if (cont.Length > 3)
                {
                    pozPct = 3;
                }
                else
                    return false;
            }
            String ContParinte = cont.Substring(0, pozPct);
            cmd.CommandText = "SELECT [Cont] FROM [Conturi] WHERE [Cont]='" + ContParinte + "' AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            Object retObj = cmd.ExecuteScalar();
            if (retObj != null && retObj != DBNull.Value)
                ret = true;
            InchideConexiune(cmd.Connection);
            cmd.Dispose();

            return ret;
        }

        private void NotaContabilaFrm_HandleRezumat(object sender, EventArgs e)
        {
            if (ModuleInfo.CurrentTheme == "tribunal")
            {
                String numarFormula = numarDocTB.Text;
                String numarNota = numarNotaCB.Text;
                //renunta la editarea inregistrarii curente
                fKarhRulajearhRulajeDocBindingSource.CancelEdit();
                arhRulajeDocBindingSource.CancelEdit();
                //incarca inregistrarea curenta
                if (numarFormula != String.Empty)
                {
                    arhRulajeDocBindingSource.Filter = "[NumarDoc]=" + numarFormula;
                }
                else
                {
                    arhRulajeDocBindingSource.Filter = String.Empty;
                    if (numarNota != String.Empty)
                    {
                        arhRulajeDocBindingSource.Filter = "[NumarNota]='" + numarNota + "'";
                    }
                }
                if (arhRulajeDocBindingSource.Count == 1)
                    return;
                if (arhRulajeDocBindingSource.Count == 0)
                    arhRulajeDocBindingSource.Filter = String.Empty;

            }
            EnableMainBrowseButton = false;
            _frmNCR = new ArhNoteContabileRezumatFrm(this.arhRulajeDocBindingSource, ModuleInfo);
            _frmNCR.LunaCurenta = bsRow.LunaCurenta;
            _frmNCR.SelectionAddOn = true;
            if (ModuleInfo.CurrentTheme != "tribunal")
            {
                _frmNCR.MdiParent = this.MdiParent;
                _frmNCR.Show();
            }
            else
            {
                arhRulajeDocBindingSource.MoveFirst();
                _frmNCR.ShowDialog();
                //this.rulajeDocBindingSource.Sort = String.Empty;
            }
            EnableMainBrowseButton = true;
        }

        private void FormatFirstRow(int tip, int RowIndex, int ColIndex)
        {
            MyTrace("FormatFirstRow(" + tip.ToString() + "," + RowIndex.ToString() + "," + ColIndex.ToString() + ")");
            switch (tip)
            {
                case 3:
                    if (rulajeDGV.Rows[RowIndex].Cells["contDebitColumn"].Value != System.DBNull.Value &&
                    rulajeDGV.Rows[RowIndex].Cells["contCreditColumn"].Value == System.DBNull.Value)
                    {
                        rulajeDGV.Columns["contCreditColumn"].Visible = false;
                        rulajeDGV.Rows[RowIndex].Cells["contCreditColumn"].Value = "N/A";
                        rulajeDGV.Columns["contDebitColumn"].Visible = true;
                        return;
                    }

                    if (rulajeDGV.Rows[RowIndex].Cells["contDebitColumn"].Value == System.DBNull.Value &&
                        rulajeDGV.Rows[RowIndex].Cells["contCreditColumn"].Value != System.DBNull.Value)
                    {
                        rulajeDGV.Columns["contDebitColumn"].Visible = false;
                        rulajeDGV.Rows[RowIndex].Cells["contDebitColumn"].Value = "N/A";
                        rulajeDGV.Columns["contCreditColumn"].Visible = true;
                        return;
                    }
                    if (rulajeDGV.Rows[RowIndex].Cells["contDebitColumn"].Value == System.DBNull.Value &&
                    rulajeDGV.Rows[RowIndex].Cells["contCreditColumn"].Value == System.DBNull.Value)
                    {
                        MessageBox.Show("Va rugam sa completati cel putin unul dintre cele 2 conturi (credit sau debit)!", "Eroare",
                                         MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);

                        rulajeDGV.ClearSelection();
                        rulajeDGV.Rows[RowIndex].Cells["contDebitColumn"].Selected = true;
                        //_blocValidate = true;
                        rulajeDGV.CurrentCell = rulajeDGV.SelectedCells[0];
                        //_blocValidate = false;                        
                        return;
                    }

                    if (rulajeDGV.Rows[RowIndex].Cells["contDebitColumn"].Value.ToString() != "N/A" &&
                    rulajeDGV.Rows[RowIndex].Cells["contCreditColumn"].Value.ToString() != "N/A")
                    {
                        if (MessageBox.Show("O nota monopartida nu poate avea cont debit si cont credit!\nNota se va transforma in nota debitoare!", "Eroare",
                            MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk) == DialogResult.OK)
                        {
                            rulajeDGV.Columns["contCreditColumn"].Visible = false;
                            rulajeDGV.Rows[RowIndex].Cells["contCreditColumn"].Value = "N/A";
                            rulajeDGV.Columns["contDebitColumn"].Visible = true;
                            return;

                        }
                    }
                    break;
            }

        }
        private void FormatNextRows(int tip, int RowIndex, int ColIndex)
        {
            MyTrace("FormatNextRows(" + tip.ToString() + "," + RowIndex.ToString() + "," + ColIndex.ToString() + ")");
            //daca este alt rand nu-l formateaza
            if (RowIndex < 1)
                return;
            switch (tip)
            {
                case 0:
                    if (rulajeDGV[contDebitColumn.Index, RowIndex].Value.ToString() != rulajeDGV[contDebitColumn.Index, 0].Value.ToString())
                    {
                        rulajeDGV[contDebitColumn.Index, RowIndex].Value = rulajeDGV[contDebitColumn.Index, 0].Value;
                        rulajeDGV[contDebitColumn.Index, RowIndex].ReadOnly = true;
                        rulajeDGV[contDebitColumn.Index, RowIndex].Style.BackColor = Color.LightGray;
                    }
                    break;
                case 1:
                    if (rulajeDGV[contCreditColumn.Index, RowIndex].Value.ToString() != rulajeDGV[contCreditColumn.Index, 0].Value.ToString())
                    {
                        rulajeDGV[contCreditColumn.Index, RowIndex].Value = rulajeDGV[contCreditColumn.Index, 0].Value;
                        rulajeDGV[contCreditColumn.Index, RowIndex].ReadOnly = true;
                        rulajeDGV[contCreditColumn.Index, RowIndex].Style.BackColor = Color.LightGray;
                    }
                    break;
                case 3:
                    if (rulajeDGV[contDebitColumn.Index, RowIndex].Visible == false)
                    {
                        if (rulajeDGV[contDebitColumn.Index, RowIndex].Value.ToString() != "N/A")
                            rulajeDGV[contDebitColumn.Index, RowIndex].Value = "N/A";
                        return;
                    }
                    if (rulajeDGV[contCreditColumn.Index, RowIndex].Visible == false)
                    {
                        if (rulajeDGV[contCreditColumn.Index, RowIndex].Value.ToString() != "N/A")
                            rulajeDGV[contCreditColumn.Index, RowIndex].Value = "N/A";
                        return;
                    }
                    break;
            }

        }


        private void RulajeFrm_HandleBeforeAdd(object sender, EventArgs e)
        {
            arhRulajeDocBindingSource.Filter = String.Empty;
            arhRulajeDocBindingSource.Sort = String.Empty;
        }

        private void FormulaContabilaFrm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (_frmNCR != null)
            {
                _frmNCR.Close();
                _frmNCR.Dispose();
            }
        }
        private void FormatGrid(int tip)
        {
            switch (tip)
            {
                case 0:
                    //cont la %
                    // nu se adauga o linie la inceputul gridului - ca nu se poate adauga
                    // in griduri binduite
                    tSB0_Click(tSB0, null);
                    break;
                case 1:
                    // % la cont
                    tSB1_Click(tSB1, null);
                    break;
                case 2:
                    ///Cont la Cont
                    tSB2_Click(tSB2, null);
                    break;
                case 3:
                    //monopartida
                    tSB3_Click(tSB3, null);
                    break;

            }
            //_dinBind = true;
        }

        #region Functii butoane tip formula
        /// <summary>
        /// butoanele pentru tipul formulei
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tSB0_Click(object sender, EventArgs e)
        {
            //Trace.Assert(this.listDataTable[BSindexMaster].GetChanges() == null, "s-a modificat ceva!!");
            DataRowView dr = ((DataRowView)arhRulajeDocBindingSource.Current);
            Int16 vTipFormula = 0;
            if (dr != null && dr["TipFormula"] != DBNull.Value)
                vTipFormula = Convert.ToInt16(dr["TipFormula"]);

            if (fKarhRulajearhRulajeDocBindingSource.Count > 1 && e != null)
            {
                MessageBox.Show("Tipul formulei contabile nu poate fi modificat \ndaca au fost adaugate linii!!", "Eroare",
                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                this.tSB0.Checked = vTipFormula == 0;
                return;
            }

            tSB0.CheckState = CheckState.Checked;
            tSB1.CheckState = CheckState.Unchecked;
            tSB2.CheckState = CheckState.Unchecked;
            tSB3.CheckState = CheckState.Unchecked;

            Int16 ind = 0;
            contCreditColumn.Visible = true;
            contDebitColumn.Visible = true;

            for (ind = 1; ind < rulajeDGV.Rows.Count; ind++)
            {
                rulajeDGV[contDebitColumn.Index, ind].ReadOnly = true;
                rulajeDGV[contDebitColumn.Index, ind].Style.BackColor = Color.LightGray;
                rulajeDGV[contCreditColumn.Index, ind].ReadOnly = false;
                rulajeDGV[contCreditColumn.Index, ind].Style.BackColor = rulajeDGV[ExplicatiiColumn.Index, ind].Style.BackColor;

            }
            if (vTipFormula != 0)
                dr["TipFormula"] = 0;
            eSRPDataSet.RulajeDoc.TipFormulaColumn.DefaultValue = 0;
        }
        private void tSB1_Click(object sender, EventArgs e)
        {
            //Trace.Assert(this.listDataTable[BSindexMaster].GetChanges() == null, "s-a modificat ceva!!");
            DataRowView dr = ((DataRowView)arhRulajeDocBindingSource.Current);
            Int16 vTipFormula = 1;
            if (dr != null && dr["TipFormula"] != DBNull.Value)
                vTipFormula = Convert.ToInt16(dr["TipFormula"]);
            if (fKarhRulajearhRulajeDocBindingSource.Count > 1 && e != null)
            {
                MessageBox.Show("Tipul formulei contabile nu poate fi modificat \ndaca au fost adaugate linii!!", "Eroare", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                this.tSB1.Checked = vTipFormula == 1;
                return;
            }

            tSB0.CheckState = CheckState.Unchecked;
            tSB1.CheckState = CheckState.Checked;
            tSB2.CheckState = CheckState.Unchecked;
            tSB3.CheckState = CheckState.Unchecked;

            Int16 ind = 0;
            contCreditColumn.Visible = true;
            contDebitColumn.Visible = true;

            for (ind = 1; ind < rulajeDGV.Rows.Count; ind++)
            {
                rulajeDGV[contCreditColumn.Index, ind].ReadOnly = true;
                rulajeDGV[contCreditColumn.Index, ind].Style.BackColor = Color.LightGray;
                rulajeDGV[contDebitColumn.Index, ind].ReadOnly = false;
                rulajeDGV[contDebitColumn.Index, ind].Style.BackColor = rulajeDGV[ExplicatiiColumn.Index, ind].Style.BackColor;
            }
            if (vTipFormula != 1)
                dr["TipFormula"] = 1;
            eSRPDataSet.RulajeDoc.TipFormulaColumn.DefaultValue = 1;
        }
        private void tSB2_Click(object sender, EventArgs e)
        {
            ToolStripButton myButton = sender as ToolStripButton;
            DataRowView dr = ((DataRowView)arhRulajeDocBindingSource.Current);
            Int16 vTipFormula = 2;
            if (dr != null && dr["TipFormula"] != DBNull.Value)
                vTipFormula = Convert.ToInt16(dr["TipFormula"]);
            if (fKarhRulajearhRulajeDocBindingSource.Count > 1 && e != null)
            {
                MessageBox.Show("Tipul formulei contabile nu poate fi modificat \ndaca au fost adaugate linii!!", "Eroare", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                this.tSB2.Checked = vTipFormula == 2;
                return;
            }

            contCreditColumn.Visible = true;
            contDebitColumn.Visible = true;

            tSB0.CheckState = CheckState.Unchecked;
            tSB1.CheckState = CheckState.Unchecked;
            tSB2.CheckState = CheckState.Checked;
            tSB3.CheckState = CheckState.Unchecked;
            Int16 ind = 0;
            for (ind = 1; ind < rulajeDGV.Rows.Count; ind++)
            {
                rulajeDGV[contCreditColumn.Index, ind].ReadOnly = false;
                rulajeDGV[contCreditColumn.Index, ind].Style.BackColor = rulajeDGV[ExplicatiiColumn.Index, ind].Style.BackColor;
                rulajeDGV[contDebitColumn.Index, ind].ReadOnly = false;
                rulajeDGV[contDebitColumn.Index, ind].Style.BackColor = rulajeDGV[ExplicatiiColumn.Index, ind].Style.BackColor;
            }
            if (vTipFormula != 2)
                dr["TipFormula"] = 2;
            eSRPDataSet.RulajeDoc.TipFormulaColumn.DefaultValue = 2;

        }
        private void tSB3_Click(object sender, EventArgs e)
        {
            //Trace.Assert(this.listDataTable[BSindexMaster].GetChanges() == null, "s-a modificat ceva!!");
            DataRowView dr = ((DataRowView)arhRulajeDocBindingSource.Current);
            Int16 vTipFormula = 3;
            if (dr != null && dr["TipFormula"] != DBNull.Value)
                vTipFormula = Convert.ToInt16(dr["TipFormula"]);
            if (fKarhRulajearhRulajeDocBindingSource.Count > 1 && e != null)
            {
                MessageBox.Show("Tipul formulei contabile nu poate fi modificat \ndaca au fost adaugate linii!!", "Eroare", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                this.tSB3.Checked = vTipFormula == 3;
                return;
            }

            tSB0.CheckState = CheckState.Unchecked;
            tSB1.CheckState = CheckState.Unchecked;
            tSB2.CheckState = CheckState.Unchecked;
            tSB3.CheckState = CheckState.Checked;
            Int16 ind = 0;
            for (ind = 1; ind < rulajeDGV.Rows.Count; ind++)
            {
                rulajeDGV.Rows[ind].Cells["contCreditColumn"].ReadOnly = false;
                rulajeDGV.Rows[ind].Cells["contCreditColumn"].Style.BackColor = rulajeDGV[ExplicatiiColumn.Index, ind].Style.BackColor;
                rulajeDGV.Rows[ind].Cells["contDebitColumn"].ReadOnly = false;
                rulajeDGV[contDebitColumn.Index, ind].Style.BackColor = rulajeDGV[ExplicatiiColumn.Index, ind].Style.BackColor;
            }
            String columnNameHide = null, columnNameShow = null;
            //daca sunt rulaje ascunde coloanele pentru monopartida
            if ((fKarhRulajearhRulajeDocBindingSource.Count > 1) ||
                (fKarhRulajearhRulajeDocBindingSource.Count == 1 && ((DataRowView)this.fKarhRulajearhRulajeDocBindingSource.CurrencyManager.Current).IsNew == false))
            {
                columnNameHide = "contDebitColumn";
                columnNameShow = "contCreditColumn";
                if (rulajeDGV.Rows[0].Cells["contCreditColumn"].Value.ToString() == "N/A")
                {
                    columnNameHide = "contCreditColumn";
                    columnNameShow = "contDebitColumn";
                }
                rulajeDGV.Columns[columnNameHide].Visible = false;
                rulajeDGV.Columns[columnNameShow].Visible = true;
            }
            else
            {
                rulajeDGV.Columns["contCreditColumn"].Visible = true;
                rulajeDGV.Columns["contDebitColumn"].Visible = true;

            }
            if (vTipFormula != 3)
                dr["TipFormula"] = 3;
            eSRPDataSet.RulajeDoc.TipFormulaColumn.DefaultValue = 3;
        }
        #endregion

        private Decimal GetSum(String numeColoana)
        {
            Decimal total = Decimal.Zero;
            foreach (DataGridViewRow dr in rulajeDGV.Rows)
            {
                if (dr.Cells[numeColoana].Value != DBNull.Value)
                    total += Convert.ToDecimal(dr.Cells[numeColoana].Value);
            }
            return total;
        }

        private void rulajeDGV_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            MyTrace("rulajeDGV_CellValueChanged " + e.RowIndex.ToString() + ",coloana=" + e.ColumnIndex.ToString());
            if (e.RowIndex == -1)
                return;
            String newVal;
            if (rulajeDGV.Columns["valoareLeiColumn"] != null)
            {
                if (rulajeDGV.Columns["valoareLeiColumn"].Index == e.ColumnIndex)
                {
                    newVal = GetSum("valoareLeiColumn").ToString("N2");
                    if (this.valoareLeiTextBox.Text != newVal)
                        this.valoareLeiTextBox.Text = newVal;
                }
            }
            if (rulajeDGV.Columns["valoareValutaColumn"] != null)
            {
                if (bsRow.FolosesteValute && rulajeDGV.Columns["valoareValutaColumn"].Index == e.ColumnIndex)
                {
                    newVal = GetSum("valoareValutaColumn").ToString("N2");
                    if (this.valoareValutaTB.Text != newVal)
                        this.valoareValutaTB.Text = this.valoareValutaTB.Text;
                }
            }
        }

        private void rulajeDGV_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            DataRowView drDoc = ((DataRowView)arhRulajeDocBindingSource.Current);
            DataRowView dr = ((DataRowView)fKarhRulajearhRulajeDocBindingSource.Current);
            if (dr == null || drDoc == null)
                return;
            Int16 tip = Convert.ToInt16(drDoc["TipFormula"].ToString());
            /// adaugare verificare pentru evitarea formatarii daca nu este cazul
            if (TipFormula == tip)
                return;
            TipFormula = tip;
            MyTrace("rulajeDGV_DataBindingComplete(" + TipFormula.ToString() + ")");
            if (tip == 0)
            {
                ContComun = dr["ContDebit"].ToString();
                eSRPDataSet.Rulaje.ContDebitColumn.DefaultValue = ContComun;
                eSRPDataSet.Rulaje.ContCreditColumn.DefaultValue = String.Empty;
            }
            if (tip == 1)
            {
                ContComun = dr["ContCredit"].ToString();
                eSRPDataSet.Rulaje.ContCreditColumn.DefaultValue = ContComun;
                eSRPDataSet.Rulaje.ContDebitColumn.DefaultValue = String.Empty;
            }
            if (tip == 2 || tip == 3)
            {
                ContComun = String.Empty;
                eSRPDataSet.Rulaje.ContCreditColumn.DefaultValue = String.Empty;
                eSRPDataSet.Rulaje.ContDebitColumn.DefaultValue = String.Empty;
            }
            FormatGrid(tip);

        }

        private void GenereazaNCBuget()
        {
            SqlCommand cmd = new SqlCommand("SELECT * FROM [Buget] WHERE [CodFormula] IS NULL AND [CodUnitate]=" + ModuleInfo.CodUnitate + " ORDER BY [DataInceput]",
                DeschideConexiune(workConnString));
            SqlDataReader dr = cmd.ExecuteReader();
            DateTime dataAnt = DateTime.Now;
            ESRPDataSet.RulajeDocRow rdd = null;
            ESRPDataSet.RulajeRow rrr = null;
            Decimal suma = Decimal.Zero;
            arhRulajeDocBindingSource.SuspendBinding();
            this.rulajeSaveBS.SuspendBinding();
            while (dr.Read())
            {
                if (dataAnt != Convert.ToDateTime(dr["DataInceput"]))
                {
                    if (rdd != null)
                    {
                        rdd.ValoareLei = suma;
                        rulajeDGV.Columns[contCreditColumn.Index].Visible = false;
                    }
                    dataAnt = Convert.ToDateTime(dr["DataInceput"]);
                    Adauga(this, null);
                    rdd = ((DataRowView)arhRulajeDocBindingSource.Current).Row
                        as ESRPDataSet.RulajeDocRow;
                    rdd.NumarDoc = Convert.ToDecimal(this.numarDocTB.Text);
                    rdd.NumarNota = "AB";
                    rdd.DataDoc = dataAnt;
                    rdd.TipFormula = 3;
                    rdd.Observatii = "Nota contabila generata pentru bugetul aprobat";
                    rdd.IDJurnal = Convert.ToInt32(dr["IDjurnal"]);

                }
                this.rulajeSaveBS.AddNew();
                rrr = ((DataRowView)rulajeSaveBS.Current).Row
                        as ESRPDataSet.RulajeRow;
                rrr.IDDocument = rdd.IDDocument;
                rrr.ContDebit = "8060." + dr["ArtAl"].ToString();
                rrr.ContCredit = "N/A";
                rrr.ValoareLei = Convert.ToDecimal(dr["Suma"]);
                rrr.DataDocJust = dataAnt;
                rrr.TipDocJust = "AB";
                suma += rrr.ValoareLei;
                rrr.ExplicatiiDocJust = "Buget aprobat la " + dataAnt.ToShortDateString();
            }
            if (rdd != null)
            {
                rdd.ValoareLei = suma;
                rulajeDGV.Columns[contCreditColumn.Index].Visible = false;
            }
            dr.Close();
            InchideConexiune(cmd.Connection);
            arhRulajeDocBindingSource.ResumeBinding();
            this.rulajeSaveBS.ResumeBinding();
            Ultimul(this, null);
        }

        override public void SetCurentUnit(short vCodUnitate)
        {
            ModuleInfo.CodUnitate = vCodUnitate;
            SqlConnection con = DeschideConexiune(workConnString);




            balconSetupTableAdapter.Connection = con;
            balconSetupTableAdapter.Fill(this.eSRPDataSet.BalconSetup, ModuleInfo.CodUnitate);
            Setup(con);
            this.arhJurnaleTableAdapter.Connection = con;
            this.arhJurnaleTableAdapter.Fill(this.arhESRPDataSet.arhJurnale, ModuleInfo.CodUnitate,Convert.ToInt16(ModuleInfo.AnArhiva));
            conturiTableAdapter.Connection = con;
            conturiTableAdapter.Fill(eSRPDataSet.Conturi, ModuleInfo.CodUnitate);
            ///in modul de generare nu incarca nici o nota contabila din baza de date
            if (_genereaza == 0)
            {
                this.arhRulajeDocTableAdapter.Connection = con;
                this.arhRulajeDocTableAdapter.Fill(this.arhESRPDataSet.arhRulajeDoc, ModuleInfo.CodUnitate, Convert.ToInt16(ModuleInfo.AnArhiva));

                this.arhRulajeTableAdapter.Connection = con;
                this.arhRulajeTableAdapter.Fill(arhESRPDataSet.arhRulaje, ModuleInfo.CodUnitate, Convert.ToInt16(ModuleInfo.AnArhiva));
                //this.rulajeDocTableAdapter.Connection = this.rulajeTableAdapter.Connection;
                //this.rulajeDocTableAdapter.FillByMonth(this.eSRPDataSet.RulajeDoc, ModuleInfo.CodUnitate, Convert.ToDecimal(bsRow.LunaCurenta));

                //this.rulajeTableAdapter.Connection = con;
                //this.rulajeTableAdapter.Fill(eSRPDataSet.Rulaje, ModuleInfo.CodUnitate);
                arhRulajeDocBindingSource.Sort = "DataDoc desc,IDDocument Desc";
            }
            arhNumarNotaRulajeDocViewTableAdapter.Connection = con;
            arhNumarNotaRulajeDocViewTableAdapter.Fill(arhESRPDataSet.arhNumarNotaRulajeDocView, ModuleInfo.CodUnitate, Convert.ToInt16(ModuleInfo.AnArhiva));
            //this.numarNotaRulajeDocViewTableAdapter.Connection = con;
            //this.numarNotaRulajeDocViewTableAdapter.Fill(this.eSRPDataSet.NumarNotaRulajeDocView, ModuleInfo.CodUnitate);
            SetSetariLocale(con, "CUSE", "0", ModuleInfo.CodUnitate);

            InchideConexiune(con);

            SetTitle();

            if (ModuleInfo.CurrentTheme == "tribunal")
            {
                if (!this.ReadOnly)
                {
                    RulajeFrm_HandleBeforeAdd(this, null);
                    Adauga(this, null);
                }
                return;
            }
            if (_genereaza == 0)
            {
                if (arhRulajeDocBindingSource.Count == 0 && !this.ReadOnly)
                {
                    RulajeFrm_HandleBeforeAdd(this, null);
                    Adauga(this, null);
                }
            }
            else
                switch (_genereaza)
                {
                    case 1:
                        GenereazaNCBuget();
                        break;
                }


        }

        private Int16 GetCategorieCont(String cont)
        {
            Int16 ret = 0;
            if (cont.Length > 0)
            {
                if (cont[0] == '8')
                    ret = 2;
                if (cont[0] == '9')
                    ret = 1;
            }
            return ret;

        }



        private void rulajeDocBindingSource_CurrentItemChanged(object sender, EventArgs e)
        {
            SetTitle();
        }

        private void rulajeDGV_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
            MyTrace("rulajeDGV_DefaultValuesNeeded");
            if (e.Row.Index >= 1)
            {
                if (bsRow.CopiazaExplicatia)
                {
                    if ((rulajeDGV[ExplicatiiColumn.Index, e.Row.Index].Value == null) ||
                        (rulajeDGV[ExplicatiiColumn.Index, e.Row.Index].Value.ToString() == String.Empty))
                        rulajeDGV[ExplicatiiColumn.Index, e.Row.Index].Value =
                            rulajeDGV[ExplicatiiColumn.Index, e.Row.Index - 1].Value;
                }
            }
        }
        /// <summary>
        /// functie apelata pentru a calcula suma in cazul stergerii unei linii
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        new public void Sterge(object sender, EventArgs args)
        {
            String newVal = GetSum("valoareLeiColumn").ToString("N2");
            if (this.valoareLeiTextBox.Text != newVal)
                this.valoareLeiTextBox.Text = newVal;
            newVal = GetSum("valoareValutaColumn").ToString("N2");
            if (this.valoareValutaTB.Text != newVal)
                this.valoareValutaTB.Text = this.valoareValutaTB.Text;

        }

        public void StergeTribunal(object sender, EventArgs args)
        {
            base.Sterge(sender, args);
            String newVal = GetSum("valoareLeiColumn").ToString("N2");
            if (this.valoareLeiTextBox.Text != newVal)
                this.valoareLeiTextBox.Text = newVal;
            newVal = GetSum("valoareValutaColumn").ToString("N2");
            if (this.valoareValutaTB.Text != newVal)
                this.valoareValutaTB.Text = this.valoareValutaTB.Text;

        }

        private void dataDocDTP_Leave(object sender, EventArgs e)
        {
            //seteaza valoare implicita pentru documentul justificativ
            eSRPDataSet.Rulaje.DataDocJustColumn.DefaultValue = dataDocDTP.Value;
        }

        private void FormulaContabilaFrm_Activated(object sender, EventArgs e)
        {
            ///seteaza butoanele active din toolbar
            ///
            EnableMainBrowseButton = true;
        }

        private void CapitoleB_Click(object sender, EventArgs e)
        {
            FrmMainMdi frm = MdiParent as FrmMainMdi;
            Assembly asm = frm.GetModule("erpforms");
            if (asm == null)
                return;

            String numeClasa = "ERPForms.JurnaleFrm";
            Type mModule = asm.GetType(numeClasa);

            if (mModule != null)
            {
                Boolean eBug = true;
                FrmRezumat newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                   new object[] { ModuleInfo, eBug }, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmRezumat;

                //newFrm.MdiParent = frm;
                newFrm.SelectionAddOn = true;
                newFrm.ShowDialog();
            }
        }

        private bool FormulaContabilaFrm_HandlerValidatingAfterEndEdit(object sender)
        {
            #region Validari RulajeDoc

            ESRPDataSet.RulajeDocDataTable dt = eSRPDataSet.RulajeDoc.GetChanges() as ESRPDataSet.RulajeDocDataTable;
            if (dt == null)
                return true;
            foreach (ESRPDataSet.RulajeDocRow dr in dt.Rows)
            {
                if (dr.RowState == DataRowState.Deleted)
                    continue;
                ESRPDataSet.RulajeRow[] docrt = eSRPDataSet.Rulaje.Select("IDDocument=" + dr.IDDocument.ToString()) as ESRPDataSet.RulajeRow[];
                if (docrt == null || docrt.Length == 0)
                {
                    MessageBoxFrm mbt = new MessageBoxFrm("Eroare validare", "Formula contabilă trebuie să aibă cel puţin o linie corectă în tabel!", String.Empty, MessageBoxFrm.ImaginiMB.StopIcon, dr);
                    mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                    mbt.ShowDialog();
                    return false;
                }
                //if (dr.NrDoc.Trim() == String.Empty)
                //{
                //    int poz = documenteBindingSource.Find("IDDocument", dr.IDDocument);
                //    if (poz != -1)
                //        documenteBindingSource.Position = poz;

                //    MessageBoxFrm mbt = new MessageBoxFrm("Eroare validare", "Vă rugăm completaţi numărul documentului!", String.Empty, dr);
                //    mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                //    mbt.ShowDialog();
                //    errorProvider1.SetError(NrDocTB, "Vă rugăm completaţi numărul documentului!");

                //    return false;
                //}

                /////Bonurile de consum nu au parteneri
                /////
                //if ((dr.IDTipDocument != 13) && (dr.IDPartener == -1))
                //{
                //    int poz = documenteBindingSource.Find("IDDocument", dr.IDDocument);
                //    if (poz != -1)
                //        documenteBindingSource.Position = poz;

                //    MessageBoxFrm mbt = new MessageBoxFrm("Eroare validare", "Vă rugăm selectaţi partenerul!", String.Empty, dr);
                //    mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                //    mbt.ShowDialog();
                //    errorProvider1.SetError(PartenerCB, "Vă rugăm selectaţi partenerul!");
                //    return false;
                //}

                //if (Bugetara && dr.IsIDJurnalNull())
                //{
                //    int poz = documenteBindingSource.Find("IDDocument", dr.IDDocument);
                //    if (poz != -1)
                //        documenteBindingSource.Position = poz;

                //    MessageBoxFrm mbt = new MessageBoxFrm("Eroare validare", "Vă rugăm selectaţi sursa de finanţare!", String.Empty, dr);
                //    mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                //    mbt.ShowDialog();

                //    errorProvider1.SetError(iDJurnalCB, "Vă rugăm selectaţi sursa de finanţare!");
                //    return false;
                //}

                //DataRow[] docDet = eSRPDataSet.DocumenteDetaliu.Select("IDDocument=" + dr.IDDocument.ToString());
                //if (docDet.Length == 0)
                //{
                //    int poz = documenteBindingSource.Find("IDDocument", dr.IDDocument);
                //    if (poz != -1)
                //        documenteBindingSource.Position = poz;

                //    MessageBoxFrm mbt = new MessageBoxFrm("Eroare validare", "Documentul trebuie să conţină cel puţin o linie corectă!", String.Empty, dr);
                //    mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                //    mbt.ShowDialog();
                //    //errorProvider1.SetError(docDetaliuDGV, "Documentul trebuie să conţină cel puţin o linie corectă!");

                //    return false;
                //}
            }




            #endregion

            #region Validare Rulaje

            ESRPDataSet.RulajeDataTable ddt = eSRPDataSet.Rulaje.GetChanges() as ESRPDataSet.RulajeDataTable;
            if (ddt == null)
                return true;
            foreach (ESRPDataSet.RulajeRow dr in ddt.Rows)
            {
                if (dr.RowState == DataRowState.Deleted)
                    continue;
                ESRPDataSet.RulajeDocRow[] docrt = eSRPDataSet.RulajeDoc.Select("IDDocument=" + dr.IDDocument.ToString()) as ESRPDataSet.RulajeDocRow[];
                if (docrt == null || docrt.Length == 0)
                    return false;
                ESRPDataSet.RulajeDocRow docr = docrt[0];

                //ESRPDataSet.DocumenteDetaliuLinkRow[] ddlr = eSRPDataSet.DocumenteDetaliuLink.Select("IDDocDetaliuDest=" + dr.IDDocumentDetaliu.ToString()) as ESRPDataSet.DocumenteDetaliuLinkRow[];

                //if ((docr.IDTipDocument == 1 || docr.IDTipDocument == 13 || docr.IDTipDocument == 14) && GestiuneaStocurilor)
                //{


                //    ESRPDataSet.ArticoleRow[] artrt = eSRPDataSet.Articole.Select("IDArticol=" + dr.IDArticol.ToString()) as ESRPDataSet.ArticoleRow[];
                //    if (artrt.Length == 0)
                //        return false;
                //    ESRPDataSet.ArticoleRow artr = artrt[0];
                //    if (artr.EsteServiciu)
                //        continue;
                //    if (ddlr.Length == 0)
                //    {
                //        int poz = documenteBindingSource.Find("IDDocument", dr.IDDocument);
                //        if (poz != -1 && documenteBindingSource.Position != poz)
                //            documenteBindingSource.Position = poz;

                //        MessageBoxFrm mbt = new MessageBoxFrm("Eroare validare", "La documentele de ieşire (pentru gestiunea stocurilor) este obligatorie specificarea stocurilor din care se face ieşirea!", String.Empty, dr);
                //        mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                //        mbt.ShowDialog();
                //        //errorProvider1.SetError(docDetaliuDGV, "Documentul trebuie să conţină cel puţin o linie corectă!");
                //        return false;
                //    }
                //    Decimal cantiesite = Decimal.Zero;
                //    foreach (ESRPDataSet.DocumenteDetaliuLinkRow i in ddlr)
                //    {
                //        cantiesite += i.Cantitate;
                //    }
                //    if (cantiesite != dr.Cantitate)
                //    {
                //        int poz = documenteBindingSource.Find("IDDocument", dr.IDDocument);
                //        if (poz != -1 && documenteBindingSource.Position != poz)
                //            documenteBindingSource.Position = poz;

                //        MessageBoxFrm mbt = new MessageBoxFrm("Eroare validare", "Cantitatea ieşită pe document diferă de cantitatea ieşită din stoc!", "Continuaţi", dr);
                //        //mbt.AddButton("Da", 70, mbt.MessageBoxFrm_Click_Yes);
                //        mbt.AddButton("Nu", 70, mbt.MessageBoxFrm_Click_No);
                //        //if(mbt.ShowDialog()== System.Windows.Forms.DialogResult.No)
                //        mbt.ShowDialog();
                //        return false;

                //    }

                //}
            }
            #endregion

            return true;
        }

        private void Copiaza(object sender, EventArgs e)
        {

            ArhESRPDataSet.arhRulajeDocRow rd = ((DataRowView)arhRulajeDocBindingSource.Current).Row as ArhESRPDataSet.arhRulajeDocRow;
            try
            {
                arhRulajeDocBindingSource.AddNew();
            }
            catch (Exception ex)
            {
                TrateazaExceptie(ex);
                return;
            }

            arhRulajeDocBindingSource.MoveLast();
            ArhESRPDataSet.arhRulajeDocRow newrd = ((DataRowView)arhRulajeDocBindingSource.Current).Row as ArhESRPDataSet.arhRulajeDocRow;
            //newrd.NumarDoc = ;
            newrd.DataDoc = rd.DataDoc;
            newrd.TipFormula = rd.TipFormula;
            if (!rd.IsIDJurnalNull())
                newrd.IDJurnal = rd.IDJurnal;
            if (!rd.IsObservatiiNull())
                newrd.Observatii = rd.Observatii;
            newrd.ValoareLei = rd.ValoareLei;
            newrd.ValoareValuta = rd.ValoareValuta;
            arhRulajeDocBindingSource.ResetCurrentItem();
            foreach (ArhESRPDataSet.arhRulajeRow rdc in arhESRPDataSet.arhRulaje.Select("IDDocument=" + rd.IDDocument.ToString()))
            {
                fKarhRulajearhRulajeDocBindingSource.AddNew();
                //documenteDetaliuBindingSource.MoveLast();
                ArhESRPDataSet.arhRulajeRow nrd = ((DataRowView)fKarhRulajearhRulajeDocBindingSource.Current).Row as ArhESRPDataSet.arhRulajeRow;
                nrd.ContDebit = rdc.ContDebit;
                nrd.ContCredit = rdc.ContCredit;
                nrd.CodValuta = rdc.CodValuta;
                nrd.IDDocument = newrd.IDDocument;
                nrd.ValoareValuta = rdc.ValoareValuta;
                nrd.Curs = rdc.Curs;
                nrd.ValoareLei = rdc.ValoareLei;
                nrd.DataDocJust = rdc.DataDocJust;
                nrd.TipDocJust = rdc.TipDocJust;
                nrd.NumarDocJust = rdc.NumarDocJust;
                nrd.ExplicatiiDocJust = rdc.ExplicatiiDocJust;
                nrd.NrCrt = 0;
            }
            fKarhRulajearhRulajeDocBindingSource.AddNew();

            fKarhRulajearhRulajeDocBindingSource.RemoveCurrent();
            fKarhRulajearhRulajeDocBindingSource.ResetCurrentItem();
            //documenteDetaliuBindingSource.MoveFirst();
            FormulaContabilaFrm_HandleAfterAdd(this, null);
            Text = numeMacheta + " - Copie Document";

        }

        


    }
}
 